package com.example.mylibrary;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class NetHelper {

    private static OkHttpClient mOkHttpClient = new OkHttpClient();

    public static Call postJson(String url, Map<String, String> posts) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            for (Map.Entry<String, String> map : posts.entrySet()) {
                json.put(map.getKey(), map.getValue());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okhttp3.Call call = mOkHttpClient.newCall(request);

        return call;
    }

    public static Call postSomething(String url, Map<String, String> posts) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormBody.Builder fb = new FormBody.Builder();
        for (Map.Entry<String, String> map : posts.entrySet()) {
            fb.add(map.getKey(), map.getValue());
        }
        RequestBody formBody = fb.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        return call;
    }

    public static Call postString(String url, String paramName, String param) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add(paramName, param)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        return call;
    }

    public static Call postString(String url, String paramName, String param, String paramName2, String param2) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add(paramName, param)
                .add(paramName2, param2)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        return call;
    }


    public static Call getSomething(String url) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = mOkHttpClient.newCall(request);
        return call;
    }

}
